import Flutter
import UIKit
import AMapFoundationKit
import AMapLocationKit
import CoreLocation

@main
@objc class AppDelegate: FlutterAppDelegate {
  
  // 高德地图服务
  private var locationManager: AMapLocationManager?
  private var clLocationManager: CLLocationManager?  // 系统位置管理器
  private var locationChannel: FlutterMethodChannel?
  
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    // 🗺️ 初始化高德地图服务
    initializeAmapServices()
    
    // 注册Flutter生成的插件
    GeneratedPluginRegistrant.register(with: self)
    
    // 🗺️ 注册高德地图服务
    registerAmapServices()
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  /**
   * 初始化高德地图服务（与Android端保持一致）
   */
  private func initializeAmapServices() {
    NSLog("🎯 =============== 初始化高德地图服务 ===============")
    
    // 从Info.plist获取API Key
    if let apiKey = Bundle.main.object(forInfoDictionaryKey: "AMapApiKey") as? String {
      NSLog("🔑 使用高德地图API Key: \(apiKey)")
      AMapServices.shared().apiKey = apiKey
      
      // 设置隐私政策同意状态
      AMapServices.shared().enableHTTPS = true
      
      // 初始化高德定位管理器
      locationManager = AMapLocationManager()
      locationManager?.delegate = self
      
      // 初始化系统定位管理器（用于权限请求）
      clLocationManager = CLLocationManager()
      clLocationManager?.delegate = self
      
      NSLog("✅ 高德地图基础服务初始化成功")
    } else {
      NSLog("❌ 未在Info.plist中找到高德地图API Key")
    }
  }
  
  /**
   * 注册高德地图Flutter服务
   */
  private func registerAmapServices() {
    NSLog("🔧 注册高德地图Flutter服务...")
    
    guard let controller = window?.rootViewController as? FlutterViewController else {
      NSLog("❌ 无法获取FlutterViewController")
      return
    }
    
    // 注册高德定位服务
    locationChannel = FlutterMethodChannel(
      name: "com.playtruly.amap_location",
      binaryMessenger: controller.binaryMessenger
    )
    
    locationChannel?.setMethodCallHandler { [weak self] (call, result) in
      self?.handleLocationMethodCall(call, result: result)
    }
    
    NSLog("✅ 高德定位服务已注册")
    NSLog("🎉 所有高德地图服务注册完成")
  }
  
  /**
   * 处理Flutter定位方法调用
   */
  private func handleLocationMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    NSLog("📞 收到Flutter调用: \(call.method)")
    
    switch call.method {
    case "requestLocation":
      handleRequestLocation(arguments: call.arguments, result: result)
    case "startLocation":
      handleStartLocation(arguments: call.arguments, result: result)
    case "stopLocation":
      handleStopLocation(result: result)
    case "isLocationServiceEnabled":
      handleIsLocationServiceEnabled(result: result)
    case "getLocationPermissionStatus":
      handleGetLocationPermissionStatus(result: result)
    case "requestLocationPermission":
      handleRequestLocationPermission(result: result)
    default:
      result(FlutterMethodNotImplemented)
    }
  }
  
  /**
   * 请求单次定位
   */
  private func handleRequestLocation(arguments: Any?, result: @escaping FlutterResult) {
    NSLog("🎯 开始单次定位")
    
    guard let locationManager = self.locationManager else {
      result(createErrorResult(message: "定位管理器未初始化"))
      return
    }
    
    // 设置定位参数
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.locationTimeout = 10
    locationManager.reGeocodeTimeout = 5
    
    // 请求单次定位
    locationManager.requestLocation(withReGeocode: true) { (location: CLLocation?, regeocode: AMapLocationReGeocode?, error: Error?) in
      self.handleLocationResponse(location: location, regeocode: regeocode, error: error, result: result)
    }
    
    NSLog("🚀 单次定位请求已发出")
  }
  
  /**
   * 开始连续定位
   */
  private func handleStartLocation(arguments: Any?, result: @escaping FlutterResult) {
    NSLog("🎯 开始连续定位")
    
    guard let locationManager = self.locationManager else {
      result(createErrorResult(message: "定位管理器未初始化"))
      return
    }
    
    // 设置定位参数
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.locationTimeout = 10
    locationManager.reGeocodeTimeout = 5
    
    // 开始连续定位
    locationManager.startUpdatingLocation()
    
    result(["success": true, "message": "连续定位已启动"])
    NSLog("🚀 连续定位已启动")
  }
  
  /**
   * 停止定位
   */
  private func handleStopLocation(result: @escaping FlutterResult) {
    NSLog("🛑 停止定位")
    
    locationManager?.stopUpdatingLocation()
    
    result(["success": true, "message": "定位已停止"])
    NSLog("🛑 定位已停止")
  }
  
  /**
   * 检查定位服务是否可用
   */
  private func handleIsLocationServiceEnabled(result: @escaping FlutterResult) {
    let isEnabled = CLLocationManager.locationServicesEnabled()
    result(["isEnabled": isEnabled])
    NSLog("📍 定位服务状态: \(isEnabled)")
  }
  
  /**
   * 获取定位权限状态
   */
  private func handleGetLocationPermissionStatus(result: @escaping FlutterResult) {
    let status = CLLocationManager.authorizationStatus()
    let permissionStatus = mapAuthorizationStatus(status)
    result(["status": permissionStatus])
    NSLog("🔐 定位权限状态: \(permissionStatus)")
  }
  
  /**
   * 请求定位权限
   */
  private func handleRequestLocationPermission(result: @escaping FlutterResult) {
    NSLog("📱 请求定位权限")
    
    guard let clLocationManager = self.clLocationManager else {
      result(createErrorResult(message: "定位管理器未初始化"))
      return
    }
    
    // 检查当前授权状态
    let status = CLLocationManager.authorizationStatus()
    NSLog("🔍 当前授权状态: \(mapAuthorizationStatus(status))")
    
    switch status {
    case .notDetermined:
      NSLog("📱 首次请求定位权限")
      clLocationManager.requestWhenInUseAuthorization()
    case .denied:
      NSLog("⚠️ 权限被拒绝，引导用户到设置")
      // 可以引导用户到设置页面
      result(["success": false, "message": "权限被拒绝，请到设置中开启位置权限"])
      return
    case .restricted:
      NSLog("⚠️ 权限受限")
      result(["success": false, "message": "位置权限受限"])
      return
    case .authorizedWhenInUse, .authorizedAlways:
      NSLog("✅ 权限已授予")
      result(["success": true, "message": "权限已授予"])
      return
    @unknown default:
      NSLog("❓ 未知权限状态")
      clLocationManager.requestWhenInUseAuthorization()
    }
    
    result(["success": true, "message": "权限请求已发出"])
  }
  
  /**
   * 处理定位结果
   */
  private func handleLocationResponse(location: CLLocation?, regeocode: AMapLocationReGeocode?, error: Error?, result: @escaping FlutterResult) {
    if let error = error {
      NSLog("❌ 定位失败: \(error.localizedDescription)")
      result(createErrorResult(message: error.localizedDescription))
    } else if let location = location {
      NSLog("✅ 定位成功: \(location.coordinate.latitude), \(location.coordinate.longitude)")
      
      // 构建返回数据格式
      var locationData: [String: Any] = [
        "latitude": location.coordinate.latitude,
        "longitude": location.coordinate.longitude,
        "accuracy": location.horizontalAccuracy,
        "altitude": location.altitude,
        "speed": location.speed,
        "bearing": location.course,
        "timestamp": Int64(location.timestamp.timeIntervalSince1970 * 1000),
        "provider": "amap_ios",
        "isSuccess": true,
        "errorCode": 0,
        "errorMessage": ""
      ]
      
      // 添加地址信息
      if let regeocode = regeocode {
        locationData["address"] = regeocode.formattedAddress ?? ""
        locationData["country"] = regeocode.country ?? ""
        locationData["province"] = regeocode.province ?? ""
        locationData["city"] = regeocode.city ?? ""
        locationData["district"] = regeocode.district ?? ""
        locationData["street"] = regeocode.street ?? ""
        locationData["streetNumber"] = regeocode.number ?? ""
        locationData["poiName"] = ""  // 高德iOS SDK的逆地理编码返回格式不同
        locationData["cityCode"] = regeocode.citycode ?? ""
        locationData["adCode"] = regeocode.adcode ?? ""
      }
      
      result(locationData)
    } else {
      NSLog("❌ 定位失败: 未知错误")
      result(createErrorResult(message: "定位失败"))
    }
  }
  
  /**
   * 映射授权状态
   */
  private func mapAuthorizationStatus(_ status: CLAuthorizationStatus) -> String {
    switch status {
    case .notDetermined:
      return "notDetermined"
    case .restricted:
      return "restricted"
    case .denied:
      return "denied"
    case .authorizedAlways:
      return "authorizedAlways"
    case .authorizedWhenInUse:
      return "authorizedWhenInUse"
    @unknown default:
      return "unknown"
    }
  }
  
  /**
   * 创建错误结果
   */
  private func createErrorResult(message: String) -> [String: Any] {
    return [
      "isSuccess": false,
      "errorCode": -1,
      "errorMessage": message,
      "latitude": 0.0,
      "longitude": 0.0,
      "provider": "amap_ios"
    ]
  }
}

// MARK: - CLLocationManagerDelegate (系统位置权限管理)

extension AppDelegate: CLLocationManagerDelegate {
  
  func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    NSLog("🔐 系统位置权限状态变更: \(mapAuthorizationStatus(status))")
    
    let permissionData = [
      "status": mapAuthorizationStatus(status),
      "isAuthorized": status == .authorizedWhenInUse || status == .authorizedAlways
    ] as [String : Any]
    
    DispatchQueue.main.async {
      self.locationChannel?.invokeMethod("onPermissionChanged", arguments: permissionData)
    }
    
    // 如果权限被授予，可以开始定位
    if status == .authorizedWhenInUse || status == .authorizedAlways {
      NSLog("✅ 位置权限已授予，可以开始定位")
    } else if status == .denied {
      NSLog("❌ 位置权限被拒绝")
    }
  }
  
  func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    NSLog("❌ 系统定位失败: \(error.localizedDescription)")
  }
}

// MARK: - AMapLocationManagerDelegate (高德地图定位)

extension AppDelegate: AMapLocationManagerDelegate {
  
  func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode!) {
    NSLog("📍 收到定位更新: \(location.coordinate.latitude), \(location.coordinate.longitude)")
    
    // 构建位置数据
    var locationData: [String: Any] = [
      "latitude": location.coordinate.latitude,
      "longitude": location.coordinate.longitude,
      "accuracy": location.horizontalAccuracy,
      "altitude": location.altitude,
      "speed": location.speed,
      "bearing": location.course,
      "timestamp": Int64(location.timestamp.timeIntervalSince1970 * 1000),
      "provider": "amap_ios",
      "isSuccess": true,
      "errorCode": 0,
      "errorMessage": ""
    ]
    
    if let regeocode = reGeocode {
      locationData["address"] = regeocode.formattedAddress ?? ""
      locationData["country"] = regeocode.country ?? ""
      locationData["province"] = regeocode.province ?? ""
      locationData["city"] = regeocode.city ?? ""
      locationData["district"] = regeocode.district ?? ""
      locationData["street"] = regeocode.street ?? ""
      locationData["streetNumber"] = regeocode.number ?? ""
      locationData["poiName"] = ""  // 高德iOS SDK的逆地理编码返回格式不同
      locationData["cityCode"] = regeocode.citycode ?? ""
      locationData["adCode"] = regeocode.adcode ?? ""
    }
    
    // 通过Channel发送到Flutter
    DispatchQueue.main.async {
      self.locationChannel?.invokeMethod("onLocationChanged", arguments: locationData)
    }
  }
  
  func amapLocationManager(_ manager: AMapLocationManager!, didFailWithError error: Error!) {
    NSLog("❌ 定位失败: \(error.localizedDescription)")
    
    let errorData = createErrorResult(message: error.localizedDescription)
    DispatchQueue.main.async {
      self.locationChannel?.invokeMethod("onLocationChanged", arguments: errorData)
    }
  }
  
  func amapLocationManager(_ manager: AMapLocationManager!, didChange status: CLAuthorizationStatus) {
    NSLog("🔐 定位权限状态变更: \(mapAuthorizationStatus(status))")
    
    let permissionData = [
      "status": mapAuthorizationStatus(status)
    ]
    
    DispatchQueue.main.async {
      self.locationChannel?.invokeMethod("onPermissionChanged", arguments: permissionData)
    }
  }
}
